﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Studio77.PopBall.Util;
using System.Windows.Media;
using Studio77.PopBall.Core;
using Studio77.PopBall.Entities;
using System.Windows.Controls.Primitives;
using Studio77.PopBall.Utils;
using Microsoft.Phone.Tasks;
using System.Windows.Threading;

namespace Studio77.PopBall.Pages
{
    public partial class GamePage : PhoneApplicationPage
    {
        public static GamePage Instance = null;

        private int currentScore = 0;

        private int currentStageIndex = 1;

        private int currentTarget = 0;

        private int currentTargetStartPoint = 0;

        /// <summary>
        /// 游戏状态 0-未开始 1-游戏中 2-游戏结束 3-暂停
        /// </summary>
        private int gameStatus = 0;

        private bool isStageClear = false;

        public bool isToolShow = false;
        public int CurrentSelectToolType { get; set; }

        public GamePage()
        {
            InitializeComponent();
            Instance = this;
            CurrentSelectToolType = 0;
            this.StoryboardHidePause.Completed += StoryboardHidePause_Completed;
        }

        void StoryboardHidePause_Completed(object sender, EventArgs e)
        {
            if (gameStatus != 3)
            {
                this.bdrPause.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (isToolShow)
            {
                btnCloseToll_Click(null, null);
            }
            else if (gameStatus == 1)
            {
                gameStatus = 3;
                StoryboardShowPause.Begin();
                this.bdrPause.Visibility = System.Windows.Visibility.Visible;
            }
            else if (gameStatus == 3)
            {
                gameStatus = 1;
                StoryboardHidePause.Begin();
            }
            else if (gameStatus == 2)
            {
                GameOverOk_Click(null, null);
            }
            e.Cancel = true;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            //保存游戏历史数据

            if (gameStatus == 1 || gameStatus == 3)
            {
                //保存游戏记录
                SavedGameData gameData = new SavedGameData();
                gameData.CurrentScore = currentScore;
                gameData.StageIndex = currentStageIndex;
                gameData.GameData = gameCanvas.GetGameData();
                StageManager.Instance.SaveData = gameData;
            }
            else if (gameStatus == 2)
            {
                //清空历史记录
                StageManager.Instance.SaveData = null;
            }


        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.NavigationMode == NavigationMode.New)
            {
                GotoMarketToComment();
            }

            base.OnNavigatedTo(e);

            if (StageManager.Instance.IsPlaySound)
            {
                this.btnSoundOn.Visibility = System.Windows.Visibility.Visible;
                this.btnSoundOff.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                this.btnSoundOn.Visibility = System.Windows.Visibility.Collapsed;
                this.btnSoundOff.Visibility = System.Windows.Visibility.Visible;
            }

            //播放背景音乐
            AudioPlayHelper.PlayBackground();
            if (gameStatus == 0)
            {
                string isNewGame = "1";
                NavigationContext.QueryString.TryGetValue("IsNewGame", out isNewGame);

                if (isNewGame == "1")
                {
                    isStageClear = false;
                    isToolShow = false;
                    currentStageIndex = 1;
                    currentTargetStartPoint = 0;
                    UpdateTarget(currentStageIndex);
                    //新游戏，从关卡1开始
                    gameCanvas.InitGame();

                    this.startView.Show(currentStageIndex, currentTarget);
                    this.StoryboardShowGameCanvas.BeginTime = TimeSpan.FromMilliseconds(2700);
                    this.StoryboardShowGameCanvas.Begin();
                    this.gameStatus = 1;

                    UpdateProgressBar();

                }
                else
                {
                    isToolShow = false;
                    //继续游戏，从上次的记录点开始
                    if (StageManager.Instance.SaveData != null)
                    {
                        currentStageIndex = StageManager.Instance.SaveData.StageIndex;
                        currentScore = StageManager.Instance.SaveData.CurrentScore;
                        currentTargetStartPoint = currentScore;
                        UpdateTarget(currentStageIndex);

                        //载入游戏进度
                        gameCanvas.ContinueGame(StageManager.Instance.SaveData.GameData);

                        this.startView.Show(currentStageIndex, currentTarget);
                        this.StoryboardShowGameCanvas.BeginTime = TimeSpan.FromMilliseconds(2700);
                        this.StoryboardShowGameCanvas.Begin();
                        this.gameStatus = 1;
                        this.txtCurrentScore.Text = currentScore.ToString();

                        isStageClear = false;
                        if (currentScore >= currentTarget)
                        {
                            isStageClear = true;
                            this.StoryboardStageClear.Begin();
                        }

                        UpdateProgressBar();
                    }
                }
            }
        }

        private void UpdateTarget(int stageIndex)
        {
            //设置目标
            currentTarget = ScoreHelper.GetTargetScore(currentStageIndex);
            this.txtTarget.Text = currentTarget.ToString();
            this.txtStage.Text = currentStageIndex.ToString();
        }

        internal void AddScore(int score, int ballCount)
        {
            HideScoreTip();
            currentScore += score;
            this.txtAddScore.Text = "+" + score;
            this.StoryboardAddScore.Begin();
            this.txtCurrentScore.Text = currentScore.ToString();

            if (StageManager.Instance.HighScore < currentScore)
            {
                StageManager.Instance.HighScore = currentScore;
            }

            
            var commentType = ScoreHelper.GetCommentType(ballCount);
            this.txtAddScoreComment.Text = ScoreHelper.GetCommentString(commentType);
            if (commentType != EliminateComment.None)
            {
                this.StoryboardShowAddDesc.Begin();
            }

            //判断是否过关
            if (currentScore >= currentTarget)
            {
                ClearStage();
            }

            UpdateProgressBar();
        }

        internal void UpdateProgressBar()
        {
            progressComplete.Visibility = System.Windows.Visibility.Visible;
            this.progressComplete.Maximum = currentTarget;
            this.progressComplete.Minimum = currentTargetStartPoint;
            this.progressComplete.Value = currentScore;
        }

        private void ClearStage()
        {
            if (!isStageClear)
            {
                isStageClear = true;
                //显示通过标志
                this.StoryboardStageClear.Begin();

                ////送一个魔法球
                //this.StoryboardAddMagicBall.Begin();
                //StageManager.Instance.MagicBallCount++;

                //音效
                SoundManager.PlayEffect(SoundManager.stageClear);
            }
        }

        public void NoEliminate()
        {
            //delay 2s 开始执行
            DispatcherTimer delay = new DispatcherTimer();
            delay.Interval = TimeSpan.FromSeconds(1);
            delay.Tick += (object sender, EventArgs e) => {
                delay.Stop();
                delay = null;
                if (currentScore < currentTarget)
                {
                    //GameOver
                    SoundManager.PlayEffect(SoundManager.failed);

                    txtGameOverScore.Text = currentScore.ToString();

                    this.StoryboardGameOver.Begin();
                    gameStatus = 2;




                    ////上传分数至排行榜
                    //Leaderboard lb = new Leaderboard(XLiveGameManager.CurrentSession, "5f3db983-d1fe-441b-8e3e-0603765b2220");
                    //lb.SubmitScoreCompleted += lb_SubmitScoreCompleted;
                    //lb.SubmitScore(this.currentScore);

                }
                else
                {


                    //进行下一个关卡
                    this.StoryboardHideGameCanvas.Begin();
                    this.StoryboardHideStageClear.Begin();
                    isToolShow = false;
                    this.StoryboardHideMagicBall.Begin();
                    this.gameCanvas.Opacity = 0;
                    this.txtCurrentScore.Opacity = 0;
                    //(this.gameCanvas.RenderTransform as CompositeTransform).TranslateY = -800;
                    currentStageIndex++;
                    UpdateTarget(currentStageIndex);
                    this.startView.Show(currentStageIndex, currentTarget);
                    this.StoryboardShowGameCanvas.BeginTime = TimeSpan.FromMilliseconds(2700);
                    this.StoryboardShowGameCanvas.Begin();

                    currentTargetStartPoint = currentScore;
                    progressComplete.Visibility = System.Windows.Visibility.Collapsed;

                    MyDispatcherTimer tempTimer = new MyDispatcherTimer();
                    tempTimer.Interval = TimeSpan.FromMilliseconds(2000);
                    tempTimer.Tick += (object ss, EventArgs ee) =>
                    {
                        tempTimer.Stop();
                        gameCanvas.RestartGame();
                    };
                    tempTimer.Start();

                    isStageClear = false;

                }
            };
            delay.Start();
        }


        internal void ShowScoreTip(int count)
        {
            this.txtSelectComment.Text = count + " BALLS " + ScoreHelper.GetScore(count) + " POINTS";
            this.StoryboardShowScoreComment.Begin();
        }

        internal void HideScoreTip()
        {
            this.txtSelectComment.Text = string.Empty;
            this.txtSelectComment.Opacity = 0;
        }

        public void HideToolArea()
        {
            btnCloseToll_Click(null, null);
        }

        private void btnCloseToll_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //关闭工具选择
            isToolShow = false;
            CurrentSelectToolType = 0;
            this.StoryboardHideMagicBall.Begin();
            SoundManager.PlayEffect(SoundManager.buttonClick);
        }

        private void btnHome_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
        }

        private void btnSoundOn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //关闭音效
            StageManager.Instance.IsPlaySound = false;
            AudioPlayHelper.StopBackground();
            this.btnSoundOn.Visibility = System.Windows.Visibility.Collapsed;
            this.btnSoundOff.Visibility = System.Windows.Visibility.Visible;
        }

        private void btnSoundOff_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //打开音效
            StageManager.Instance.IsPlaySound = true;
            AudioPlayHelper.PlayBackground();
            this.btnSoundOn.Visibility = System.Windows.Visibility.Visible;
            this.btnSoundOff.Visibility = System.Windows.Visibility.Collapsed;
        }

        /// <summary>
        /// 去市场评价
        /// </summary>
        private void GotoMarketToComment()
        {
            if (!StageManager.Instance.IsCommented && StageManager.Instance.LaunchCount > 15)
            {
                if (MessageBox.Show("Do you like the game? Please rate it, Thanks!", "Rating", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
                    marketplaceReviewTask.Show();
                    StageManager.Instance.IsCommented = true;
                }
                else
                {
                    StageManager.Instance.LaunchCount = StageManager.Instance.LaunchCount + 1;
                    StageManager.Instance.IsCommented = true;
                }
            }
        }

        private void btnResume_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (gameStatus == 3)
            {
                gameStatus = 1;
                this.StoryboardHidePause.Begin();
            }
        }

        private void btnMainMenu_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (this.NavigationService.CanGoBack)
            {
                this.NavigationService.GoBack();
            }
            else
            {
                this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
            }
        }

        private void GameOverOk_Click(object sender, RoutedEventArgs e)
        {
            if (gameStatus == 2)
            {
                //跳转到主界面
                this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
            }
        }

        private void adControl_ErrorOccurred(object sender, Microsoft.Advertising.AdErrorEventArgs e)
        {
            adControl.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void adControl_AdRefreshed(object sender, EventArgs e)
        {
            adControl.Visibility = System.Windows.Visibility.Visible;
        }

        private void imgRuneMaster_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
        	MarketplaceDetailTask task = new MarketplaceDetailTask();
            task.ContentIdentifier = "7ce7f5ea-739b-44bb-aa6b-e28679251c2e";
            task.ContentType = MarketplaceContentType.Applications;
            task.Show();
        }
    }
}